package cn.lnexin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class WeatherHttpUtil {
	private static final String KEY = "e0260f05a4ef45b3bd6b71b24508c213";
	private static final String URL = "https://free-api.heweather.com/s6/weather/forecast";
	
	public static String getWeather(String city_name) {
		// 参数字符串，如果拼接在请求链接之后，需要对中文进行 URLEncode 字符集 UTF-8
		StringBuffer params = new StringBuffer();
		params.append("key=").append(KEY);
		params.append("&location=").append(city_name);
		StringBuilder sb = new StringBuilder();
		InputStream is = null;
		BufferedReader br = null;
		try {
			// 接口地址
			URL uri = new URL(URL);
			HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
			connection.setRequestMethod("POST");
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(10000);
			connection.setRequestProperty("accept", "*/*");
			// 发送参数
			connection.setDoOutput(true);
			PrintWriter out = new PrintWriter(connection.getOutputStream());
			out.print(params.toString());
			out.flush();
			// 接收结果
			is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String line;
			// 缓冲逐行读取
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			if (out != null) {
				out.close();
			}
			return sb.toString();
		} catch (Exception ignored) {
		} finally {
			// 关闭流
			try {
				if (is != null) {
					is.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException e2) {
			}
		}
		return null;
	}
}
